@page "/database-connection/details/{Id}"
@using Text2Sql.Net.Domain.Model
@using Text2Sql.Net.Repositories.Text2Sql
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseConnection
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseSchema
@using Text2Sql.Net.Domain.Interface

@inject IDatabaseConnectionConfigRepository DatabaseConnectionConfigRepository
@inject ISchemaTrainingService SchemaTrainingService
@inject IDatabaseSchemaRepository DatabaseSchemaRepository
@inject MessageService MessageService
@inject NavigationManager NavigationManager

<PageContainer Title="数据库连接详情">
    <ChildContent>
        <Card Loading="@_loading">
            <Descriptions Title="连接详情" Layout="@DescriptionsLayout.Horizontal" Bordered>
                <DescriptionsItem Title="连接名称" Span="3">
                    @_model.Name
                </DescriptionsItem>
                <DescriptionsItem Title="数据库类型" Span="3">
                    @_model.DbType
                </DescriptionsItem>
                <DescriptionsItem Title="连接字符串" Span="3">
                    @_model.ConnectionString
                </DescriptionsItem>
                <DescriptionsItem Title="描述" Span="3">
                    @(!string.IsNullOrEmpty(_model.Description) ? _model.Description : "-")
                </DescriptionsItem>
                <DescriptionsItem Title="创建时间" Span="3">
                    @_model.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                </DescriptionsItem>
                @if (_model.UpdateTime.HasValue)
                {
                    <DescriptionsItem Title="更新时间" Span="3">
                        @_model.UpdateTime?.ToString("yyyy-MM-dd HH:mm:ss")
                    </DescriptionsItem>
                }
            </Descriptions>
            @if (_hasTrainedSchema)
            {
                <div style="margin-top: 16px;">
                    <Alert Type="@AlertType.Info" 
                           Message="Schema状态提示" 
                           Description="此连接已有训练的Schema数据。如果您修改了数据库连接信息（如数据库名称、连接字符串等），建议重新训练Schema以确保数据一致性。" 
                           ShowIcon="true" 
                           Closable="true" />
                </div>
            }
            
            <div style="margin-top: 16px;">
                <Button Type="@ButtonType.Primary" Style="margin-right: 8px;" OnClick="@(() => NavigateToChat(Id))">
                    <Icon Type="@IconType.Outline.Comment" />
                    使用
                </Button>
                <Button Type="@ButtonType.Primary" Style="margin-right: 8px;" Loading="@_trainingLoading" OnClick="@TrainDatabaseSchema">
                    训练全部表
                </Button>
                <Button Type="@ButtonType.Default" Style="margin-right: 8px;" OnClick="@(() => NavigateToSelectTables(Id))">
                    选择表训练
                </Button>
                <Button Type="@ButtonType.Default" Style="margin-right: 8px;" OnClick="@(() => NavigateToTrainedTables(Id))">
                    <Icon Type="@IconType.Outline.Table" />
                    查看已训练表
                </Button>
                <Button Type="@ButtonType.Primary" OnClick="@(() => NavigateToEdit(Id))">
                    编辑
                </Button>
                <Button Style="margin-left: 8px;" OnClick="@NavigateToList">
                    返回
                </Button>
            </div>
        </Card>
    </ChildContent>
</PageContainer>

@code {
    [Parameter]
    public string Id { get; set; } = string.Empty;

    private DatabaseConnectionConfig _model = new DatabaseConnectionConfig();
    private bool _loading = false;
    private bool _trainingLoading = false;
    private bool _hasTrainedSchema = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadData();
    }

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            var data = await DatabaseConnectionConfigRepository.GetByIdAsync(Id);
            if (data != null)
            {
                _model = data;
                
                // 检查是否存在已训练的Schema
                var existingSchema = await DatabaseSchemaRepository.GetByConnectionIdAsync(Id);
                _hasTrainedSchema = existingSchema != null;
            }
            else
            {
                _= MessageService.Error("找不到指定的数据库连接配置");
                NavigateToList();
            }
        }
        catch (Exception ex)
        {
            _= MessageService.Error($"加载数据失败: {ex.Message}");
            NavigateToList();
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    private async Task TrainDatabaseSchema()
    {
        _trainingLoading = true;
        try
        {
            var result = await SchemaTrainingService.TrainDatabaseSchemaAsync(Id);
            if (result)
            {
                _= MessageService.Success("数据库Schema训练成功，可点击查看已训练表按钮查看结果");
                _hasTrainedSchema = true; // 更新状态
            }
            else
            {
                _= MessageService.Error("数据库Schema训练失败");
            }
        }
        catch (Exception ex)
        {
            _= MessageService.Error($"训练失败: {ex.Message}");
        }
        finally
        {
            _trainingLoading = false;
            StateHasChanged();
        }
    }

    private void NavigateToEdit(string id)
    {
        NavigationManager.NavigateTo($"/database-connection/create/{id}");
    }

    private void NavigateToSelectTables(string id)
    {
        NavigationManager.NavigateTo($"/database-connection/select-tables/{id}");
    }

    private void NavigateToTrainedTables(string id)
    {
        NavigationManager.NavigateTo($"/database-connection/trained-tables/{id}");
    }

    private void NavigateToChat(string id)
    {
        NavigationManager.NavigateTo($"/database-chat?connectionId={id}");
    }

    private void NavigateToList()
    {
        NavigationManager.NavigateTo("/database-connection");
    }
} 